/**
 * 技能配置助手
 * 提供技能配置的指导和验证功能
 */

import { ISkillConfig, SkillConfigValidator, SkillConfigExamples } from './SkillFieldDefinitions';
import { SkillType, TargetType } from '../../../shared/face/enums';
import BattleLogger from '../BattleLogger';

/**
 * 技能配置助手类
 */
export class SkillConfigHelper {
    /**
     * 生成技能配置模板
     * @param skillType 技能类型
     * @returns 技能配置模板
     */
    public static generateSkillTemplate(skillType: SkillType): ISkillConfig {
        const baseTemplate: ISkillConfig = {
            id: "",
            name: "",
            description: "",
            type: skillType,
            targetTypes: [],
            cooldown: 0,
            level: 1,
            maxLevel: 10,
            exp: 0,
            useCount: 0,
            quality: 1,
            classType: "",
            notBuy: false,
            effect: [],
            data: []
        };

        // 根据技能类型设置默认值
        switch (skillType) {
            case SkillType.主动技能:
                baseTemplate.cooldown = 2;
                baseTemplate.targetTypes = [TargetType.敌方];
                baseTemplate.effect = ["伤害"];
                baseTemplate.data = [{
                    attRange: 1.0,
                    fixed: 20
                }];
                baseTemplate.classType = "攻击";
                break;

            case SkillType.被动技能:
                baseTemplate.cooldown = 0;
                baseTemplate.targetTypes = [TargetType.自己];
                baseTemplate.effect = ["属性修改"];
                baseTemplate.data = [{
                    attributeModify: {
                        attack: 5
                    }
                }];
                baseTemplate.classType = "被动";
                break;

            case SkillType.光环技能:
                baseTemplate.cooldown = 0;
                baseTemplate.targetTypes = [TargetType.我方不含自己];
                baseTemplate.effect = ["属性修改"];
                baseTemplate.data = [{
                    attributeModify: {
                        attack: 10
                    }
                }];
                baseTemplate.classType = "光环";
                break;
        }

        return baseTemplate;
    }

    /**
     * 验证技能配置
     * @param config 技能配置
     * @returns 验证结果
     */
    public static validateSkillConfig(config: ISkillConfig): {
        isValid: boolean;
        errors: string[];
        warnings: string[];
        suggestions: string[];
    } {
        const validation = SkillConfigValidator.validate(config);
        const suggestions: string[] = [];

        // 添加改进建议
        if (config.id && !/^[A-Z]+\d+$/.test(config.id)) {
            suggestions.push('建议技能ID使用大写字母+数字格式，如 A001, P002');
        }

        if (config.cooldown === 0 && config.type === SkillType.主动技能) {
            suggestions.push('主动技能建议设置适当的冷却时间');
        }

        if (config.cooldown > 0 && config.type === SkillType.被动技能) {
            suggestions.push('被动技能通常不需要冷却时间');
        }

        if (!config.permanentBoost && config.type === SkillType.主动技能) {
            suggestions.push('考虑添加永久提升效果，增加技能的成长性');
        }

        if (config.quality === undefined) {
            suggestions.push('建议设置技能品质，影响稀有度');
        }

        return {
            ...validation,
            suggestions
        };
    }

    /**
     * 获取字段帮助信息
     * @param fieldName 字段名
     * @returns 帮助信息
     */
    public static getFieldHelp(fieldName: string): {
        description: string;
        examples: string[];
        tips: string[];
    } {
        const helpData: Record<string, any> = {
            id: {
                description: '技能唯一标识符',
                examples: ['A001', 'P002', 'AU0001'],
                tips: [
                    '使用大写字母+数字格式',
                    '建议按类型分类：A=主动，P=被动，AU=光环',
                    '保持ID的唯一性'
                ]
            },
            name: {
                description: '技能名称',
                examples: ['火焰箭', '治愈术', '勇气光环'],
                tips: [
                    '使用简洁明了的名称',
                    '体现技能的主要功能',
                    '避免过于复杂的名称'
                ]
            },
            description: {
                description: '技能描述',
                examples: ['对敌人造成火焰伤害', '恢复目标生命值'],
                tips: [
                    '描述技能的主要效果',
                    '会被动态描述系统扩展',
                    '保持描述的准确性'
                ]
            },
            type: {
                description: '技能类型',
                examples: ['主动技能', '被动技能', '光环技能'],
                tips: [
                    '主动技能：需要主动使用',
                    '被动技能：自动触发',
                    '光环技能：持续效果'
                ]
            },
            targetTypes: {
                description: '目标类型',
                examples: ['敌方', '我方', '自己', '我方不含自己'],
                tips: [
                    '可以设置多个目标类型',
                    '确保目标类型与技能效果匹配',
                    '被动技能通常选择"自己"'
                ]
            },
            cooldown: {
                description: '冷却时间（回合数）',
                examples: ['0', '1', '2', '3'],
                tips: [
                    '0表示无冷却',
                    '主动技能通常有冷却时间',
                    '被动技能通常无冷却'
                ]
            },
            effect: {
                description: '技能效果列表',
                examples: ['["伤害"]', '["治疗", "护盾"]'],
                tips: [
                    '每个效果对应一个目标',
                    '效果数组长度必须与数据数组相同',
                    '使用系统支持的效果类型'
                ]
            },
            data: {
                description: '技能数据列表',
                examples: ['[{attRange: 1.2, fixed: 30}]'],
                tips: [
                    '包含具体的数值和参数',
                    '数组长度必须与效果数组相同',
                    '数据要与效果类型匹配'
                ]
            },
            permanentBoost: {
                description: '永久提升配置',
                examples: ['{type: "damage", amount: 1}'],
                tips: [
                    '每次使用技能后的永久提升',
                    '增加技能的成长性',
                    '设置合理的提升数值'
                ]
            }
        };

        return helpData[fieldName] || {
            description: '未知字段',
            examples: [],
            tips: []
        };
    }

    /**
     * 生成技能配置示例
     * @param skillType 技能类型
     * @returns 配置示例
     */
    public static getSkillExample(skillType: SkillType): ISkillConfig {
        switch (skillType) {
            case SkillType.主动技能:
                return SkillConfigExamples.activeAttack;
            case SkillType.被动技能:
                return SkillConfigExamples.passive;
            case SkillType.光环技能:
                return SkillConfigExamples.aura;
            default:
                return SkillConfigExamples.activeAttack;
        }
    }

    /**
     * 生成技能配置文档
     * @param config 技能配置
     * @returns 配置文档
     */
    public static generateConfigDocumentation(config: ISkillConfig): string {
        const validation = this.validateSkillConfig(config);
        
        let doc = `# 技能配置文档\n\n`;
        doc += `## 基本信息\n`;
        doc += `- **ID**: ${config.id}\n`;
        doc += `- **名称**: ${config.name}\n`;
        doc += `- **类型**: ${config.type}\n`;
        doc += `- **描述**: ${config.description}\n\n`;

        doc += `## 配置详情\n`;
        doc += `- **目标类型**: ${config.targetTypes.join(', ')}\n`;
        doc += `- **冷却时间**: ${config.cooldown} 回合\n`;
        doc += `- **等级**: ${config.level || 1}/${config.maxLevel || 10}\n`;
        doc += `- **品质**: ${config.quality || 1}\n`;
        doc += `- **分类**: ${config.classType || '未设置'}\n\n`;

        doc += `## 效果配置\n`;
        config.effect.forEach((effect, index) => {
            doc += `### 效果 ${index + 1}\n`;
            doc += `- **效果类型**: ${effect}\n`;
            doc += `- **数据**: ${JSON.stringify(config.data[index], null, 2)}\n\n`;
        });

        if (config.permanentBoost) {
            doc += `## 永久提升\n`;
            doc += `- **类型**: ${config.permanentBoost.type}\n`;
            doc += `- **数值**: ${config.permanentBoost.amount}\n`;
            if (config.permanentBoost.maxBoosts) {
                doc += `- **最大次数**: ${config.permanentBoost.maxBoosts}\n`;
            }
            doc += `\n`;
        }

        if (config.buffs && config.buffs.length > 0) {
            doc += `## Buff配置\n`;
            config.buffs.forEach((buff, index) => {
                doc += `### Buff ${index + 1}\n`;
                doc += `- **ID**: ${buff.id}\n`;
                doc += `- **持续时间**: ${buff.duration} 回合\n`;
                if (buff.maxStacks) {
                    doc += `- **最大层数**: ${buff.maxStacks}\n`;
                }
                if (buff.value) {
                    doc += `- **效果数值**: ${buff.value}\n`;
                }
                doc += `\n`;
            });
        }

        doc += `## 验证结果\n`;
        if (validation.isValid) {
            doc += `✅ **配置有效**\n\n`;
        } else {
            doc += `❌ **配置有误**\n`;
            validation.errors.forEach(error => {
                doc += `- ${error}\n`;
            });
            doc += `\n`;
        }

        if (validation.warnings.length > 0) {
            doc += `⚠️ **警告**\n`;
            validation.warnings.forEach(warning => {
                doc += `- ${warning}\n`;
            });
            doc += `\n`;
        }

        if (validation.suggestions.length > 0) {
            doc += `💡 **建议**\n`;
            validation.suggestions.forEach(suggestion => {
                doc += `- ${suggestion}\n`;
            });
            doc += `\n`;
        }

        return doc;
    }

    /**
     * 获取所有字段的完整帮助信息
     * @returns 所有字段的帮助信息
     */
    public static getAllFieldHelp(): Record<string, any> {
        const fields = [
            'id', 'name', 'description', 'type', 'targetTypes', 'cooldown',
            'level', 'maxLevel', 'exp', 'useCount', 'quality', 'classType',
            'notBuy', 'effect', 'data', 'permanentBoost', 'buffs'
        ];

        const help: Record<string, any> = {};
        fields.forEach(field => {
            help[field] = this.getFieldHelp(field);
        });

        return help;
    }

    /**
     * 创建技能配置向导
     * @param skillType 技能类型
     * @returns 配置向导步骤
     */
    public static createConfigWizard(skillType: SkillType): {
        steps: Array<{
            step: number;
            field: string;
            description: string;
            required: boolean;
            examples: string[];
        }>;
        template: ISkillConfig;
    } {
        const template = this.generateSkillTemplate(skillType);
        
        const steps = [
            {
                step: 1,
                field: 'id',
                description: '设置技能唯一标识符',
                required: true,
                examples: ['A001', 'P002', 'AU0001']
            },
            {
                step: 2,
                field: 'name',
                description: '设置技能名称',
                required: true,
                examples: ['火焰箭', '治愈术', '勇气光环']
            },
            {
                step: 3,
                field: 'description',
                description: '设置技能描述',
                required: true,
                examples: ['对敌人造成火焰伤害', '恢复目标生命值']
            },
            {
                step: 4,
                field: 'targetTypes',
                description: '设置目标类型',
                required: true,
                examples: ['敌方', '我方', '自己']
            },
            {
                step: 5,
                field: 'cooldown',
                description: '设置冷却时间',
                required: false,
                examples: ['0', '1', '2', '3']
            },
            {
                step: 6,
                field: 'effect',
                description: '设置技能效果',
                required: true,
                examples: ['["伤害"]', '["治疗"]', '["属性修改"]']
            },
            {
                step: 7,
                field: 'data',
                description: '设置效果数据',
                required: true,
                examples: ['[{attRange: 1.2, fixed: 30}]']
            },
            {
                step: 8,
                field: 'permanentBoost',
                description: '设置永久提升（可选）',
                required: false,
                examples: ['{type: "damage", amount: 1}']
            }
        ];

        return { steps, template };
    }
} 